<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{

    const PERSONAL_MAX_USER_AMOUNT = 2;

    const REPAIRING = -1; //维修审核中
    const USABLE = 0; //正常
    const REFUNDING = 1; //退款审核中
    const REFUNDED = 2; //已退款

    public static $statusArr = [
        self::REPAIRING => '维修审核中',
        self::USABLE => '正常',
        self::REFUNDING => '退款审核中',
        self::REFUNDED => '已退租',
    ];

    public $fillable = [
        'slug', 'name', 'owner_id', 'max_user_amount', 'status', 'device_type', 'device_id'
    ];


    public function owner()
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function device()
    {
        return $this->morphTo();
    }


    //判断用户的柜子是否是公司的柜子
    public function isCompany()
    {
        $device = $this->device_type;
        if (strpos($device,'Chest') !== false) {
            return true;
        }else{
            return false;
        }

    }

    public function getSlug($type = '')
    {

        $slug = $this->slug ? $this->slug : '0_0_0';

        $data = explode('_', $slug);
        if (!$type) {
            return $data;
        }
        $typeArr = [
            'group' => 0,
            'chest' => 1,
            'grip' => 2
        ];
        $flag = array_get($typeArr, $type);
        return array_get($data, $flag, 0);
    }

    public function getHumanStatusAttribute()
    {
        return array_get(self::$statusArr, $this->status);
    }

    // 申请退款
    public function refund()
    {
        if ($this->isUsable()) {
            $this->update([
                'status' => self::REFUNDING
            ]);
        }
    }

    // 退款
    public function refunded()
    {
        if ($this->isRefunding()) {
            $this->update([
                'status' => self::REFUNDED
            ]);
        }
    }
    //撤销退款
    public function cancel()
    {
        if ($this->isRefunding()) {
            $this->update([
                'status' => self::USABLE
            ]);
        }
    }

    //维修
    public function repair()
    {
        if ($this->isUsable()) {
            $this->update([
                'status' => self::REPAIRING
            ]);
        }
    }

    //是否可用 只有可用状态的group 才可申请退款
    public function isUsable()
    {
        return self::USABLE == $this->status;
    }

    // 是否正在申请退款
    public function isRefunding()
    {

        return self::REFUNDING == $this->status;
    }

    //是否已经退款
    public function isRefunded()
    {
        return self::REFUNDED == $this->status;
    }
    //获取该租人数
    public function count()
    {
      return GroupUser::where(['group_id'=>$this->id])->count();
    }


}